# coding: utf-8
import requests#type: ignore
from iamtoken import get_token
import base64
import recordaudio
url = "https://sis-ext.cn-north-4.myhuaweicloud.com/v1/7703c099b8f5485985140d72ce89715a/asr/short-audio"
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials#type: ignore
from huaweicloudsdksis.v1.region.sis_region import SisRegion#type: ignore
from huaweicloudsdkcore.exceptions import exceptions#type: ignore
from huaweicloudsdksis.v1 import *#type: ignore
from iamtoken import ak, sk
def stt(AUDIO_ROOT):
    with open(AUDIO_ROOT, "rb") as f:
        base64str = base64.b64encode(f.read()).decode()
        credentials = BasicCredentials(ak, sk)
        client = SisClient.new_builder().with_credentials(credentials).with_region(SisRegion.value_of("cn-north-4")).build()#type: ignore
        try:
            request = RecognizeShortAudioRequest()#type: ignore
            configbody = Config(#type: ignore
                audio_format="pcm16k16bit",
                _property="chinese_16k_general"
            )
            request.body = PostShortAudioReq(#type: ignore
                data=base64str,
                config=configbody
            )
            response = client.recognize_short_audio(request)
            print(response)
            return response.result.text
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
            return "识别失败"
def continualStt():
    for file in recordaudio.continualRecord():
        yield stt(file)
        
def main():
    if os.path.exists("/opt"):
        recordaudio.main(True)
        return stt("recorded.pcm")
    else:
        return input("请告诉我你想做什么:")
if __name__ == "__main__":
    main()

